using JGSY.CourseManagement.Domain.Interfaces;
using JGSY.CourseManagement.Infrastructure.Configuration;
using JGSY.CourseManagement.Infrastructure.Configuration.JGSY.CourseManagement.Infrastructure.Configuration;
using JGSY.CourseManagement.Infrastructure.Data.EntityFramework;
using JGSY.CourseManagement.Infrastructure.Data.Repositories;
using JGSY.CourseManagement.Infrastructure.Messaging;
using JGSY.CourseManagement.Infrastructure.Security;
using JGSY.CourseManagement.Infrastructure.Services;
using JGSY.CourseManagement.SharedKernel.Exceptions.ExceptionHandling;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Configuration;

namespace JGSY.CourseManagement.Infrastructure.DependencyInjection
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddApplicationServices(this IServiceCollection services)
        {
            services.AddScoped<UserSessionService>()
                    .AddHostedService<SessionCleanupService>()
                    .AddSingleton<ModuleManager>()
                    .AddScoped<DatabaseMigrator>();

            return services;
        }

        public static IServiceCollection AddRepositories(this IServiceCollection services)
        {
            services.AddScoped<IUserRepository, UserRepository>();
            services.AddScoped<IUserSessionRepository, UserSessionRepository>();

            // 用户登录状态管理
            services.AddScoped<UserSessionService>();
            return services;
        }



        public static IServiceCollection AddMVVMFramework(this IServiceCollection services, IConfiguration configuration)
        {
            // 绑定配置到强类型对象
            //services.Configure<AppSettings>(configuration);
            services.Configure<AppSettings>(configuration)
                .AddInfrastructureServices(configuration)
                .AddApplicationServices()
                .AddExceptionHandling();

            return services;
        }

        public static IServiceCollection AddExceptionHandling(this IServiceCollection services)
        {
            services.AddSingleton<ExceptionHandler>();
            return services;
        }
        public static void ApplyDatabaseMigrations(this IServiceProvider serviceProvider)
        {
            try
            {
                using var scope = serviceProvider.CreateScope();
                scope.ServiceProvider.GetRequiredService<SqlServerDbContext>().Database.Migrate();
                scope.ServiceProvider.GetRequiredService<SessionDbContext>().Database.EnsureDeleted();
                scope.ServiceProvider.GetRequiredService<SessionDbContext>().Database.Migrate();
            }
            catch (Exception ex)
            {
                var migrator = serviceProvider.GetRequiredService<DatabaseMigrator>();
                migrator.LogMigrationError(ex);
                throw;
            }
        }
      

        public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddSingleton<IConfigurationService, JsonConfigurationService>()
                    .AddSingleton<IMessageBus, MessageBus>()
                    .AddDatabaseServices(configuration)
                    .AddRepositories();

            return services;
        }
        public static IServiceCollection AddDatabaseServices(this IServiceCollection services, IConfiguration configuration)
        { 
            // 使用选项模式获取配置
            services.AddSqlServerDbContext(configuration, "ConnectionStrings:MainDataConnection")
                    .AddSqliteDbContext(configuration, "ConnectionStrings:UserSessionConnection");
            return services;
        }

        // 修改数据库上下文注册方法，接受完整配置路径
        public static IServiceCollection AddSqlServerDbContext(
            this IServiceCollection services,
            IConfiguration configuration,
            string configurationPath,
            Action<DbContextOptionsBuilder>? optionsAction = null)
        {
            var connectionString = configuration[configurationPath]
                ?? throw new InvalidOperationException($"未找到配置路径 '{configurationPath}' 的值");

            services.AddDbContext<SqlServerDbContext>(options =>
            {
                options.UseSqlServer(connectionString, sqlOptions =>
                {
                    sqlOptions.CommandTimeout(30);
                    sqlOptions.EnableRetryOnFailure();
                });

                optionsAction?.Invoke(options);
            });

            return services;
        }


        // 类似地修改SQLite上下文注册方法
        public static IServiceCollection AddSqliteDbContext(
            this IServiceCollection services,
            IConfiguration configuration,
            string configurationPath,
            Action<DbContextOptionsBuilder>? optionsAction = null)
        {
            var connectionString = configuration[configurationPath]
                ?? throw new InvalidOperationException($"未找到配置路径 '{configurationPath}' 的值");

            services.AddDbContext<SessionDbContext>(options =>
            {
                options.UseSqlite(connectionString);
                optionsAction?.Invoke(options);
            });

            return services;
        }

        public static void InitializeExceptionHandling(this IServiceProvider serviceProvider)
        {
            serviceProvider.GetRequiredService<ExceptionHandler>().RegisterGlobalHandlers();
        }
    }
}